
#include "masked_fill_custom_tiling.h"
#include "register/op_def_registry.h"
#include "graph/utils/type_utils.h"
#include "tiling/platform/platform_ascendc.h"

namespace optiling {
const uint32_t BLOCK_SIZE = 32;
const uint32_t BUFFER_NUM = 2;
void TilingParamsCalc(uint32_t length, uint32_t alignNum, uint32_t tileBlockNum,
                      uint32_t &tileNum, uint32_t &tileLength, uint32_t &lastTileLength)
{
    if(length == 0) {
        tileNum =0;
        tileLength = 0;
        lastTileLength = 0;
        return;
    }
    uint32_t max_ub_num = tileBlockNum / BUFFER_NUM * BUFFER_NUM;
    tileNum = length / (alignNum * max_ub_num);
    if ((static_cast<uint32_t>(length / alignNum) % max_ub_num == 0U) || tileNum == 0U) {
        if (tileNum == 0U) {
            tileNum = 1U;
        }
        if (length < max_ub_num * alignNum) {
            tileLength = ((static_cast<size_t>(length) / alignNum) + 1) / BUFFER_NUM * BUFFER_NUM * alignNum;
            lastTileLength = tileLength;
        }
        else {
            tileLength = max_ub_num * alignNum;
            lastTileLength = (uint32_t)(length - (tileNum - 1) * tileLength);
        }
    }
    else {
        tileNum++;
        tileLength = max_ub_num * alignNum;
        lastTileLength = (uint32_t)(length - (tileNum - 1) * tileLength);
    }
}
static ge::graphStatus TilingFunc(gert::TilingContext* context)
{
    MaskedFillCustomTilingData tiling;
    uint32_t data_x = 1;
    uint32_t data_mask = 1;
    uint32_t sShape[128]= {0};
    uint32_t maskShape[128]= {0};
    uint64_t ubSize;

    auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo());
    ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize);
    auto coreNum = ascendcPlatform.GetCoreNum();

    const auto x_shape = context->GetInputShape(0);
    const auto mask_shape = context->GetInputShape(1);
    
    //set shape
    uint32_t xNumShapes = x_shape->GetStorageShape().GetDimNum();
    uint32_t maskNumShapes = mask_shape->GetStorageShape().GetDimNum();

    for (int i = 0; i < xNumShapes; i++){
        sShape[i] = x_shape->GetStorageShape().GetDim(i);
        data_x *= sShape[i];
    }
    for (int i = 0; i < maskNumShapes; i++){
        maskShape[i] = mask_shape->GetStorageShape().GetDim(i);
        data_mask *= maskShape[i];
    }

    if (maskNumShapes > xNumShapes) {
        return ge::GRAPH_FAILED;
    } 
    else {
        int align_start = xNumShapes - maskNumShapes;
        for (int i = 0; i < maskNumShapes; ++i) {
            uint32_t x_dim = sShape[align_start + i]; 
            uint32_t mask_dim = maskShape[i];       
            if (x_dim != mask_dim && x_dim != 1 && mask_dim != 1) {
                return ge::GRAPH_FAILED;
            }
        }
    }

    tiling.set_xSize(data_x);
    tiling.set_maskSize(data_mask);
    tiling.set_xNumShapes(xNumShapes);
    tiling.set_maskNumShapes(maskNumShapes);
    tiling.set_sShape(sShape);
    tiling.set_maskShape(maskShape);

    // Based on the input length and the number of inputs, the number of bytes of the input data type is obtained
    uint32_t inputBytes = 0;
    ge::TypeUtils::GetDataTypeLength(context->GetInputDesc(0)->GetDataType(), inputBytes);

    // There are a total of 3 shared UB spaces in the input and output. If it's int8, there are 2 more TBUFs
    uint32_t ubDataNumber = (inputBytes == 1) ? 5 : 3;
    // The number of 32B data blocks that can be used for each data. DOUBLE BUFFER is already counted here
    uint32_t tileBlockNum = (ubSize / BLOCK_SIZE / BUFFER_NUM) / ubDataNumber;

    uint32_t alignNum_x = BLOCK_SIZE / inputBytes;
    uint32_t alignNum_mask = BLOCK_SIZE / sizeof(bool);

    uint32_t totalLength = data_x;
    uint32_t totalLengthAligned = (totalLength % alignNum_mask == 0U) ? static_cast<uint32_t>(totalLength) : ((static_cast<uint32_t>(totalLength) + alignNum_mask - 1) / alignNum_mask) * alignNum_mask;

    uint32_t formerNum = (totalLengthAligned / alignNum_mask) % coreNum;
    uint32_t tailNum = coreNum - formerNum;

    uint32_t formerLength;
    uint32_t tailLength = (totalLengthAligned / coreNum / alignNum_mask) * alignNum_mask;
    if(formerNum == 0) {
        formerLength = 0;
    }
        
    else{
        formerLength = 
        static_cast<uint32_t>(((totalLengthAligned + coreNum - 1) / coreNum + alignNum_mask - 1) / alignNum_mask) * alignNum_mask;
    }
    uint32_t formerTileNum;
    uint32_t formerTileLength;
    uint32_t formerLastTileLength;

    uint32_t tailTileNum;
    uint32_t tailTileLength;
    uint32_t tailLastTileLength;

    TilingParamsCalc(formerLength, alignNum_x, tileBlockNum,
                         formerTileNum, formerTileLength, formerLastTileLength);
    TilingParamsCalc(tailLength, alignNum_x, tileBlockNum,
                         tailTileNum, tailTileLength, tailLastTileLength);    
    
    tiling.set_inputBytes(inputBytes);

    tiling.set_formerNum(formerNum);
    tiling.set_formerLength(formerLength);
    tiling.set_formerTileNum(formerTileNum);
    tiling.set_formerTileLength(formerTileLength);
    tiling.set_formerLastTileLength(formerLastTileLength);
    tiling.set_tailLength(tailLength);
    tiling.set_tailTileNum(tailTileNum);
    tiling.set_tailTileLength(tailTileLength);
    tiling.set_tailLastTileLength(tailLastTileLength);

    context->SetBlockDim(coreNum);
    tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity());
    context->GetRawTilingData()->SetDataSize(tiling.GetDataSize());
    size_t *currentWorkspace = context->GetWorkspaceSizes(1);
    currentWorkspace[0] = 0;
    return ge::GRAPH_SUCCESS;
}
}


namespace ge {
static ge::graphStatus InferShape(gert::InferShapeContext* context)
{
    const gert::Shape* x1_shape = context->GetInputShape(0);
    gert::Shape* y_shape = context->GetOutputShape(0);
    *y_shape = *x1_shape;
    return GRAPH_SUCCESS;
}
static ge::graphStatus InferDataType(gert::InferDataTypeContext *context)
{
    const auto inputDataType = context->GetInputDataType(0);
    context->SetOutputDataType(0, inputDataType);
    return ge::GRAPH_SUCCESS;
}
}


namespace ops {
class MaskedFillCustom : public OpDef {
public:
    explicit MaskedFillCustom(const char* name) : OpDef(name)
    {
        this->Input("x")
            .ParamType(REQUIRED)
            .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_DOUBLE, ge::DT_UINT8, ge::DT_UINT16, ge::DT_UINT32, ge::DT_UINT64, ge::DT_INT8, ge::DT_INT16, ge::DT_INT32, ge::DT_INT64, ge::DT_BOOL})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});
        this->Input("mask")
            .ParamType(REQUIRED)
            .DataTypeList({ge::DT_BOOL})
            .FormatList({ge::FORMAT_ND});
        this->Input("value")
            .ParamType(REQUIRED)
            .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_DOUBLE, ge::DT_UINT8, ge::DT_UINT16, ge::DT_UINT32, ge::DT_UINT64, ge::DT_INT8, ge::DT_INT16, ge::DT_INT32, ge::DT_INT64, ge::DT_BOOL})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});
        this->Output("z")
            .ParamType(REQUIRED)
            .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_DOUBLE, ge::DT_UINT8, ge::DT_UINT16, ge::DT_UINT32, ge::DT_UINT64, ge::DT_INT8, ge::DT_INT16, ge::DT_INT32, ge::DT_INT64, ge::DT_BOOL})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});        
        this->SetInferShape(ge::InferShape).SetInferDataType(ge::InferDataType);

        this->AICore()
            .SetTiling(optiling::TilingFunc);
        this->AICore()
            .AddConfig("ascend910b")
            .AddConfig("ascend910")
            .AddConfig("ascend310b")
            .AddConfig("ascend310p");
    }
};

OP_ADD(MaskedFillCustom);
}
